import json
import time
import redis
import os
from utils.utilities import message_head


class RedisHelper:
    def __init__(self, host, port):
        self.redis_client = redis.Redis(host=host, port=port)

    def get_list_length(self, list_name):
        while True:
            try:
                return self.redis_client.llen(list_name)
            except Exception as e:
                print(message_head(1) + "redis获取队列长度失败，操作队列名称：" + list_name)
                print(message_head(1), e)
                time.sleep(60)

    def get_set_length(self, set_name):
        while True:
            try:
                return self.redis_client.scard(set_name)
            except Exception as e:
                print(message_head(1) + "redis获取集合长度失败，操作队列名称：" + set_name)
                print(message_head(1), e)
                time.sleep(60)

    def write_list(self, list_name, value):
        while True:
            try:
                self.redis_client.lpush(list_name, json.dumps(value))
                break
            except Exception as e:
                print(message_head(1) + "redis写入错误，操作队列名称：" + list_name)
                print(message_head(1), e)
                print(message_head(1), value)
                time.sleep(60)

    def write_set(self, set_name, value):
        self.redis_client.sadd(set_name, value)

    def read_list(self, list_name):
        while True:
            try:
                content = self.redis_client.rpop(list_name)
                return json.loads(content) if content is not None else None
            except Exception as e:
                print(message_head(1) + "redis读取错误，操作队列名称：" + list_name)
                print(message_head(1), e)
                time.sleep(60)

    def read_set(self, set_name):
        return self.redis_client.spop(set_name)

    def delete_list(self, list_name):
        self.redis_client.delete(list_name)

    def delete_set(self, set_name):
        self.redis_client.smembers(set_name)
